home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / sunbird / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2007-05-23  |  98.5 KB  |  3,036 lines

  1. //@line 42 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  10. const PREF_APP_UPDATE_URL                 = "app.update.url";
  11. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  12. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  13. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  14. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  15. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  16. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  17. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  18. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  19. const PREF_PARTNER_BRANCH                 = "app.partner.";
  20.  
  21. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  22. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  23. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  24. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  25. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  26.  
  27. const KEY_APPDIR          = "XCurProcD";
  28. //@line 72 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  29.  
  30. const DIR_UPDATES         = "updates";
  31. const FILE_UPDATE_STATUS  = "update.status";
  32. const FILE_UPDATE_ARCHIVE = "update.mar";
  33. const FILE_UPDATE_LOG     = "update.log"
  34. const FILE_UPDATES_DB     = "updates.xml";
  35. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  36. const FILE_PERMS_TEST     = "update.test";
  37. const FILE_LAST_LOG       = "last-update.log";
  38.  
  39. const MODE_RDONLY   = 0x01;
  40. const MODE_WRONLY   = 0x02;
  41. const MODE_CREATE   = 0x08;
  42. const MODE_APPEND   = 0x10;
  43. const MODE_TRUNCATE = 0x20;
  44.  
  45. const PERMS_FILE      = 0644;
  46. const PERMS_DIRECTORY = 0755;
  47.  
  48. const STATE_NONE            = "null";
  49. const STATE_DOWNLOADING     = "downloading";
  50. const STATE_PENDING         = "pending";
  51. const STATE_APPLYING        = "applying";
  52. const STATE_SUCCEEDED       = "succeeded";
  53. const STATE_DOWNLOAD_FAILED = "download-failed";
  54. const STATE_FAILED          = "failed";
  55.  
  56. // From updater/errors.h:
  57. const WRITE_ERROR = 7;
  58.  
  59. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  60. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  61. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  62.  
  63. // Values for the PREF_APP_UPDATE_INCOMPATIBLE_MODE pref. See documentation in
  64. // code below. 
  65. const INCOMPATIBLE_MODE_NEWVERSIONS   = 0;
  66. const INCOMPATIBLE_MODE_NONEWVERSIONS = 1;
  67.  
  68. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  69.  
  70. const nsILocalFile            = Components.interfaces.nsILocalFile;
  71. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  72. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  73. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  74. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  75. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  76. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  77. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  78.  
  79. const Node = Components.interfaces.nsIDOMNode;
  80.  
  81. var gApp        = null;
  82. var gPref       = null;
  83. var gABI        = null;
  84. var gOSVersion  = null;
  85. var gConsole    = null;
  86. var gLogEnabled = { };
  87.  
  88. // shared code for suppressing bad cert dialogs
  89. //@line 40 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/shared/src/badCertHandler.js"
  90.  
  91. /**
  92.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  93.  */
  94. function checkCert(channel) {
  95.   if (!channel.originalURI.schemeIs("https"))  // bypass
  96.     return;
  97.  
  98.   const Ci = Components.interfaces;  
  99.   var cert =
  100.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  101.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  102.  
  103.   var issuer = cert.issuer;
  104.   while (issuer && !cert.equals(issuer)) {
  105.     cert = issuer;
  106.     issuer = cert.issuer;
  107.   }
  108.  
  109.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  110.     throw "cert issuer is not built-in";
  111. }
  112.  
  113. /**
  114.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  115.  * security dialogs from being shown to the user.  It is better to simply fail
  116.  * if the certificate is bad. See bug 304286.
  117.  */
  118. function BadCertHandler() {
  119. }
  120. BadCertHandler.prototype = {
  121.  
  122.   // nsIBadCertListener
  123.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  124.     LOG("EM BadCertHandler: Unknown issuer");
  125.     return false;
  126.   },
  127.  
  128.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  129.     LOG("EM BadCertHandler: Mismatched domain");
  130.     return false;
  131.   },
  132.  
  133.   confirmCertExpired: function(socketInfo, cert) {
  134.     LOG("EM BadCertHandler: Expired certificate");
  135.     return false;
  136.   },
  137.  
  138.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  139.   },
  140.  
  141.   // nsIChannelEventSink
  142.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  143.     // make sure the certificate of the old channel checks out before we follow
  144.     // a redirect from it.  See bug 340198.
  145.     checkCert(oldChannel);
  146.   },
  147.  
  148.   // nsIInterfaceRequestor
  149.   getInterface: function(iid) {
  150.     return this.QueryInterface(iid);
  151.   },
  152.  
  153.   // nsISupports
  154.   QueryInterface: function(iid) {
  155.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  156.         !iid.equals(Components.interfaces.nsIChannelEventSink) &&
  157.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  158.         !iid.equals(Components.interfaces.nsISupports))
  159.       throw Components.results.NS_ERROR_NO_INTERFACE;
  160.     return this;
  161.   }
  162. };
  163. //@line 133 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  164.  
  165. /**
  166.  * Logs a string to the error console. 
  167.  * @param   string
  168.  *          The string to write to the error console..
  169.  */  
  170. function LOG(module, string) {
  171.   if (module in gLogEnabled || "all" in gLogEnabled) {
  172.     dump("*** " + module + ": " + string + "\n");
  173.     gConsole.logStringMessage(string);
  174.   }
  175. }
  176.  
  177. /**
  178.  * Convert a string containing binary values to hex.
  179.  */
  180. function binaryToHex(input) {
  181.   var result = "";
  182.   for (var i = 0; i < input.length; ++i) {
  183.     var hex = input.charCodeAt(i).toString(16);
  184.     if (hex.length == 1)
  185.       hex = "0" + hex;
  186.     result += hex;
  187.   }
  188.   return result;
  189. }
  190.  
  191. /**
  192.  * Gets a File URL spec for a nsIFile
  193.  * @param   file
  194.  *          The file to get a file URL spec to
  195.  * @returns The file URL spec to the file
  196.  */
  197. function getURLSpecFromFile(file) {
  198.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  199.                          .getService(Components.interfaces.nsIIOService);
  200.   var fph = ioServ.getProtocolHandler("file")
  201.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  202.   return fph.getURLSpecFromFile(file);
  203. }
  204.  
  205. /**
  206.  * Gets the specified directory at the specified hierarchy under a 
  207.  * Directory Service key. 
  208.  * @param   key
  209.  *          The Directory Service Key to start from
  210.  * @param   pathArray
  211.  *          An array of path components to locate beneath the directory 
  212.  *          specified by |key|
  213.  * @return  nsIFile object for the location specified. If the directory
  214.  *          requested does not exist, it is created, along with any
  215.  *          parent directories that need to be created.
  216.  */
  217. function getDir(key, pathArray) {
  218.   return getDirInternal(key, pathArray, true, false);
  219. }
  220.  
  221. /**
  222.  * Gets the specified directory at the speciifed hierarchy under a 
  223.  * Directory Service key. 
  224.  * @param   key
  225.  *          The Directory Service Key to start from
  226.  * @param   pathArray
  227.  *          An array of path components to locate beneath the directory 
  228.  *          specified by |key|
  229.  * @return  nsIFile object for the location specified. If the directory
  230.  *          requested does not exist, it is NOT created.
  231.  */
  232. function getDirNoCreate(key, pathArray) {
  233.   return getDirInternal(key, pathArray, false, false);
  234. }
  235.  
  236. /**
  237.  * Gets the specified directory at the specified hierarchy under the 
  238.  * update root directory.
  239.  * @param   pathArray
  240.  *          An array of path components to locate beneath the directory 
  241.  *          specified by |key|
  242.  * @return  nsIFile object for the location specified. If the directory
  243.  *          requested does not exist, it is created, along with any
  244.  *          parent directories that need to be created.
  245.  */
  246. function getUpdateDir(pathArray) {
  247.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  248. }
  249.  
  250. /**
  251.  * Gets the specified directory at the speciifed hierarchy under a 
  252.  * Directory Service key. 
  253.  * @param   key
  254.  *          The Directory Service Key to start from
  255.  * @param   pathArray
  256.  *          An array of path components to locate beneath the directory 
  257.  *          specified by |key|
  258.  * @param   shouldCreate
  259.  *          true if the directory hierarchy specified in |pathArray|
  260.  *          should be created if it does not exist,
  261.  *          false otherwise.
  262.  * @param   update
  263.  *          true if finding the update directory,
  264.  *          false otherwise.
  265.  * @return  nsIFile object for the location specified. 
  266.  */
  267. function getDirInternal(key, pathArray, shouldCreate, update) {
  268.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  269.                               .getService(Components.interfaces.nsIProperties);
  270.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  271. //@line 248 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  272.   for (var i = 0; i < pathArray.length; ++i) {
  273.     dir.append(pathArray[i]);
  274.     if (shouldCreate && !dir.exists())
  275.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  276.   }
  277.   return dir;
  278. }
  279.  
  280. /**
  281.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  282.  * @param   key
  283.  *          The Directory Service Key to start from
  284.  * @param   pathArray
  285.  *          An array of path components to locate beneath the directory 
  286.  *          specified by |key|. The last item in this array must be the
  287.  *          leaf name of a file.
  288.  * @return  nsIFile object for the file specified. The file is NOT created
  289.  *          if it does not exist, however all required directories along 
  290.  *          the way are.
  291.  */
  292. function getFile(key, pathArray) {
  293.   var file = getDir(key, pathArray.slice(0, -1));
  294.   file.append(pathArray[pathArray.length - 1]);
  295.   return file;
  296. }
  297.  
  298. /**
  299.  * Gets the file at the speciifed hierarchy under the update root directory.
  300.  * @param   pathArray
  301.  *          An array of path components to locate beneath the directory 
  302.  *          specified by |key|. The last item in this array must be the
  303.  *          leaf name of a file.
  304.  * @return  nsIFile object for the file specified. The file is NOT created
  305.  *          if it does not exist, however all required directories along 
  306.  *          the way are.
  307.  */
  308. function getUpdateFile(pathArray) {
  309.   var file = getUpdateDir(pathArray.slice(0, -1));
  310.   file.append(pathArray[pathArray.length - 1]);
  311.   return file;
  312. }
  313.  
  314. /**
  315.  * Closes a Safe Output Stream
  316.  * @param   fos
  317.  *          The Safe Output Stream to close
  318.  */
  319. function closeSafeOutputStream(fos) {
  320.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  321.     try {
  322.       fos.finish();
  323.     }
  324.     catch (e) {
  325.       fos.close();
  326.     }
  327.   }
  328.   else
  329.     fos.close();
  330. }
  331.  
  332. /**
  333.  * Returns human readable status text from the updates.properties bundle
  334.  * based on an error code
  335.  * @param   code
  336.  *          The error code to look up human readable status text for
  337.  * @param   defaultCode
  338.  *          The default code to look up should human readable status text
  339.  *          not exist for |code|
  340.  * @returns A human readable status text string
  341.  */
  342. function getStatusTextFromCode(code, defaultCode) {
  343.   var sbs = 
  344.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  345.       getService(Components.interfaces.nsIStringBundleService);
  346.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  347.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  348.   try {
  349.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  350.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  351.   }
  352.   catch (e) {
  353.     // Use the default reason
  354.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  355.   }
  356.   return reason;
  357. }
  358.  
  359. /**
  360.  * Get the Active Updates directory
  361.  * @param   key
  362.  *          The Directory Service Key (optional).
  363.  *          If used, don't search local appdata on Win32 and don't create dir.
  364.  * @returns The active updates directory, as a nsIFile object
  365.  */
  366. function getUpdatesDir(key) {
  367.   // Right now, we only support downloading one patch at a time, so we always
  368.   // use the same target directory.
  369.   var fileLocator =
  370.       Components.classes["@mozilla.org/file/directory_service;1"].
  371.       getService(Components.interfaces.nsIProperties);
  372.   var appDir;
  373.   if (key)
  374.     appDir = fileLocator.get(key, Components.interfaces.nsIFile);
  375.   else {
  376.     appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  377. //@line 359 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  378.   }
  379.   appDir.append(DIR_UPDATES);
  380.   appDir.append("0");
  381.   if (!appDir.exists() && !key)
  382.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  383.   return appDir;
  384. }
  385.  
  386. /**
  387.  * Reads the update state from the update.status file in the specified
  388.  * directory.
  389.  * @param   dir
  390.  *          The dir to look for an update.status file in
  391.  * @returns The status value of the update.
  392.  */
  393. function readStatusFile(dir) {
  394.   var statusFile = dir.clone();
  395.   statusFile.append(FILE_UPDATE_STATUS);
  396.   LOG("General", "Reading Status File: " + statusFile.path);
  397.   return readStringFromFile(statusFile) || STATE_NONE;
  398. }
  399.  
  400. /**
  401.  * Writes the current update operation/state to a file in the patch 
  402.  * directory, indicating to the patching system that operations need
  403.  * to be performed.
  404.  * @param   dir
  405.  *          The patch directory where the update.status file should be 
  406.  *          written.
  407.  * @param   state
  408.  *          The state value to write.
  409.  */
  410. function writeStatusFile(dir, state) {
  411.   var statusFile = dir.clone();
  412.   statusFile.append(FILE_UPDATE_STATUS);
  413.   writeStringToFile(statusFile, state);
  414. }
  415.  
  416. /**
  417.  * Removes the Updates Directory
  418.  * @param   key
  419.  *          The Directory Service Key under which update directory resides
  420.  *          (optional).
  421.  */
  422. function cleanUpUpdatesDir(key) {
  423.   // Bail out if we don't have appropriate permissions
  424.   var updateDir;
  425.   try {
  426.     updateDir = getUpdatesDir(key);
  427.   }
  428.   catch (e) {
  429.     return;
  430.   }
  431.  
  432.   var e = updateDir.directoryEntries;
  433.   while (e.hasMoreElements()) {
  434.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  435.     // Preserve the last update log file for debugging purposes
  436.     if (f.leafName == FILE_UPDATE_LOG) {
  437.       try {
  438.         var dir = f.parent.parent;
  439.         var logFile = dir.clone();
  440.         logFile.append(FILE_LAST_LOG);
  441.         if (logFile.exists())
  442.           logFile.remove(false);
  443.         f.copyTo(dir, FILE_LAST_LOG);
  444.       }
  445.       catch (e) {
  446.         LOG("General", "Failed to copy file: " + f.path);
  447.       }
  448.     }
  449.     // Now, recursively remove this file.  The recusive removal is really
  450.     // only needed on Mac OSX because this directory will contain a copy of
  451.     // updater.app, which is itself a directory.
  452.     try {
  453.       f.remove(true);
  454.     }
  455.     catch (e) {
  456.       LOG("General", "Failed to remove file: " + f.path);
  457.     }
  458.   }
  459.   try {
  460.     updateDir.remove(false);
  461.   } catch (e) {
  462.     LOG("General", "Failed to remove update directory: " + updateDir.path + 
  463.         " - This is almost always bad. Exception = " + e);
  464.     throw e;
  465.   }
  466. }
  467.  
  468. /**
  469.  * Clean up updates list and the updates directory.
  470.  * @param   key
  471.  *          The Directory Service Key under which update directory resides
  472.  *          (optional).
  473.  */
  474. function cleanupActiveUpdate(key) {
  475.   // Move the update from the Active Update list into the Past Updates list.
  476.   var um = 
  477.       Components.classes["@mozilla.org/updates/update-manager;1"].
  478.       getService(Components.interfaces.nsIUpdateManager);
  479.   um.activeUpdate = null;
  480.   um.saveUpdates();
  481.  
  482.   // Now trash the updates directory, since we're done with it
  483.   cleanUpUpdatesDir(key);
  484. }
  485.  
  486. /**
  487.  * Gets a preference value, handling the case where there is no default.
  488.  * @param   func
  489.  *          The name of the preference function to call, on nsIPrefBranch
  490.  * @param   preference
  491.  *          The name of the preference
  492.  * @param   defaultValue
  493.  *          The default value to return in the event the preference has 
  494.  *          no setting
  495.  * @returns The value of the preference, or undefined if there was no
  496.  *          user or default value.
  497.  */
  498. function getPref(func, preference, defaultValue) {
  499.   try {
  500.     return gPref[func](preference);
  501.   }
  502.   catch (e) {
  503.   }
  504.   return defaultValue;
  505. }
  506.  
  507. /**
  508.  * Gets the current value of the locale.  It's possible for this preference to
  509.  * be localized, so we have to do a little extra work here.  Similar code
  510.  * exists in nsHttpHandler.cpp when building the UA string.
  511.  */
  512. function getLocale() {
  513.   try {
  514.     return gPref.getComplexValue(PREF_GENERAL_USERAGENT_LOCALE,
  515.                                  nsIPrefLocalizedString).data;
  516.   } catch (e) {}
  517.  
  518.   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  519. }
  520.  
  521. /**
  522.  * Read the update channel from defaults only.  We do this to ensure that
  523.  * the channel is tightly coupled with the application and does not apply
  524.  * to other instances of the application that may use the same profile.
  525.  */
  526. function getUpdateChannel() {
  527.   var channel = "default";
  528.   var prefName;
  529.   var prefValue;
  530.  
  531.   var defaults =
  532.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  533.       getDefaultBranch(null);
  534.   try {
  535.     channel = defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  536.   } catch (e) {
  537.     // use default when pref not found
  538.   }
  539.  
  540.   try {
  541.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  542.     if (partners.length) {
  543.       channel += "-cck";
  544.       partners.sort();
  545.  
  546.       for each (prefName in partners) {
  547.         prefValue = gPref.getCharPref(prefName);
  548.         channel += "-" + prefValue;
  549.       }
  550.     }
  551.   }
  552.   catch (e) {
  553.     Components.utils.reportError(e);
  554.   }
  555.  
  556.   return channel;
  557. }
  558.  
  559. /**
  560.  * An enumeration of items in a JS array.
  561.  * @constructor
  562.  */
  563. function ArrayEnumerator(aItems) {
  564.   this._index = 0;
  565.   if (aItems) {
  566.     for (var i = 0; i < aItems.length; ++i) {
  567.       if (!aItems[i])
  568.         aItems.splice(i, 1);      
  569.     }
  570.   }
  571.   this._contents = aItems;
  572. }
  573.  
  574. ArrayEnumerator.prototype = {
  575.   _index: 0,
  576.   _contents: [],
  577.   
  578.   hasMoreElements: function() {
  579.     return this._index < this._contents.length;
  580.   },
  581.   
  582.   getNext: function() {
  583.     return this._contents[this._index++];      
  584.   }
  585. };
  586.  
  587. /**
  588.  * Trims a prefix from a string.
  589.  * @param   string
  590.  *          The source string
  591.  * @param   prefix
  592.  *          The prefix to remove.
  593.  * @returns The suffix (string - prefix)
  594.  */
  595. function stripPrefix(string, prefix) {
  596.   return string.substr(prefix.length);
  597. }
  598.  
  599. /**
  600.  * Writes a string of text to a file.  A newline will be appended to the data
  601.  * written to the file.  This function only works with ASCII text.
  602.  */
  603. function writeStringToFile(file, text) {
  604.   var fos =
  605.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  606.       createInstance(nsIFileOutputStream);
  607.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  608.   if (!file.exists()) 
  609.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  610.   fos.init(file, modeFlags, PERMS_FILE, 0);
  611.   text += "\n";
  612.   fos.write(text, text.length);    
  613.   closeSafeOutputStream(fos);
  614. }
  615.  
  616. /**
  617.  * Reads a string of text from a file.  A trailing newline will be removed
  618.  * before the result is returned.  This function only works with ASCII text.
  619.  */
  620. function readStringFromFile(file) {
  621.   var fis =
  622.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  623.       createInstance(nsIFileInputStream);
  624.   var modeFlags = MODE_RDONLY;
  625.   if (!file.exists())
  626.     return null;
  627.   fis.init(file, modeFlags, PERMS_FILE, 0);
  628.   var sis =
  629.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  630.       createInstance(Components.interfaces.nsIScriptableInputStream);
  631.   sis.init(fis);
  632.   var text = sis.read(sis.available());
  633.   sis.close();
  634.   if (text[text.length - 1] == "\n")
  635.     text = text.slice(0, -1);
  636.   return text;
  637. }
  638.  
  639. function getObserverService()
  640. {
  641.   return Components.classes["@mozilla.org/observer-service;1"]
  642.                    .getService(Components.interfaces.nsIObserverService);
  643. }
  644.  
  645. /**
  646.  * Update Patch
  647.  * @param   patch
  648.  *          A <patch> element to initialize this object with
  649.  * @throws if patch has a size of 0
  650.  * @constructor
  651.  */
  652. function UpdatePatch(patch) {
  653.   this._properties = {};
  654.   for (var i = 0; i < patch.attributes.length; ++i) {
  655.     var attr = patch.attributes.item(i);
  656.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  657.     switch (attr.name) {
  658.     case "selected":
  659.       this.selected = attr.value == "true";
  660.       break;
  661.     case "size":
  662.       if (0 == parseInt(attr.value)) {
  663.         LOG("UpdatePatch", "0-sized patch!");
  664.         throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  665.       }
  666.       // fall through
  667.     default:
  668.       this[attr.name] = attr.value;
  669.       break;
  670.     };
  671.   }
  672. }
  673. UpdatePatch.prototype = {
  674.   /**
  675.    * See nsIUpdateService.idl
  676.    */
  677.   serialize: function(updates) {
  678.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  679.     patch.setAttribute("type", this.type);
  680.     patch.setAttribute("URL", this.URL);
  681.     patch.setAttribute("hashFunction", this.hashFunction);
  682.     patch.setAttribute("hashValue", this.hashValue);
  683.     patch.setAttribute("size", this.size);
  684.     patch.setAttribute("selected", this.selected);
  685.     patch.setAttribute("state", this.state);
  686.     
  687.     for (var p in this._properties) {
  688.       if (this._properties[p].present)
  689.         patch.setAttribute(p, this._properties[p].data);
  690.     }
  691.     
  692.     return patch; 
  693.   },
  694.   
  695.   /**
  696.    * A hash of custom properties
  697.    */
  698.   _properties: null,
  699.   
  700.   /**
  701.    * See nsIWritablePropertyBag.idl
  702.    */
  703.   setProperty: function(name, value) {
  704.     this._properties[name] = { data: value, present: true };
  705.   },
  706.   
  707.   /**
  708.    * See nsIWritablePropertyBag.idl
  709.    */
  710.   deleteProperty: function(name) {
  711.     if (name in this._properties)
  712.       this._properties[name].present = false;
  713.     else
  714.       throw Components.results.NS_ERROR_FAILURE;
  715.   },
  716.   
  717.   /**
  718.    * See nsIPropertyBag.idl
  719.    */
  720.   get enumerator() {
  721.     var properties = [];
  722.     for (var p in this._properties)
  723.       properties.push(this._properties[p].data);
  724.     return new ArrayEnumerator(properties);
  725.   },
  726.   
  727.   /**
  728.    * See nsIPropertyBag.idl
  729.    */
  730.   getProperty: function(name) {
  731.     if (name in this._properties &&
  732.         this._properties[name].present)
  733.       return this._properties[name].data;
  734.     throw Components.results.NS_ERROR_FAILURE;
  735.   },
  736.   
  737.   /**
  738.    * Returns whether or not the update.status file for this patch exists at the 
  739.    * appropriate location. 
  740.    */
  741.   get statusFileExists() {
  742.     var statusFile = getUpdatesDir();
  743.     statusFile.append(FILE_UPDATE_STATUS);
  744.     return statusFile.exists();
  745.   },
  746.   
  747.   /**
  748.    * See nsIUpdateService.idl
  749.    */
  750.   get state() {
  751.     if (!this.statusFileExists)
  752.       return STATE_NONE;
  753.     return this._properties.state;
  754.   },
  755.   set state(val) {
  756.     this._properties.state = val;
  757.   },
  758.   
  759.   /**
  760.    * See nsISupports.idl
  761.    */
  762.   QueryInterface: function(iid) {
  763.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  764.         !iid.equals(Components.interfaces.nsIPropertyBag) && 
  765.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) && 
  766.         !iid.equals(Components.interfaces.nsISupports))
  767.       throw Components.results.NS_ERROR_NO_INTERFACE;
  768.     return this;
  769.   }
  770. };
  771.  
  772. /**
  773.  * Update
  774.  * Implements nsIUpdate
  775.  * @param   update
  776.  *          An <update> element to initialize this object with
  777.  * @throws if the update contains no patches
  778.  * @constructor
  779.  */
  780. function Update(update) {
  781.   this._properties = {};
  782.   this._patches = [];
  783.   this.installDate = 0;
  784.   this.isCompleteUpdate = false;
  785.   this.channel = "default"
  786.  
  787.   // Null <update>, assume this is a message container and do no 
  788.   // further initialization
  789.   if (!update)
  790.     return;
  791.     
  792.   for (var i = 0; i < update.childNodes.length; ++i) {
  793.     var patchElement = update.childNodes.item(i);
  794.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  795.         patchElement.localName != "patch")
  796.       continue;
  797.  
  798.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  799.     try {
  800.       var patch = new UpdatePatch(patchElement);
  801.     } catch (e) {
  802.       continue;
  803.     }
  804.     this._patches.push(patch);
  805.   }
  806.   
  807.   if (0 == this._patches.length)
  808.     throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  809.  
  810.   for (var i = 0; i < update.attributes.length; ++i) {
  811.     var attr = update.attributes.item(i);
  812.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  813.     if (attr.name == "installDate" && attr.value) 
  814.       this.installDate = parseInt(attr.value);
  815.     else if (attr.name == "isCompleteUpdate")
  816.       this.isCompleteUpdate = attr.value == "true";
  817.     else if (attr.name == "isSecurityUpdate")
  818.       this.isSecurityUpdate = attr.value == "true";
  819.     else if (attr.name == "detailsURL")
  820.       this._detailsURL = attr.value;
  821.     else if (attr.name == "channel")
  822.       this.channel = attr.value;
  823.     else
  824.       this[attr.name] = attr.value;
  825.   }
  826.   
  827.   // The Update Name is either the string provided by the <update> element, or
  828.   // the string: "<App Name> <Update App Version>"
  829.   var name = "";
  830.   if (update.hasAttribute("name"))
  831.     name = update.getAttribute("name");
  832.   else {
  833.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  834.                         .getService(Components.interfaces.nsIStringBundleService);
  835.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  836.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  837.     var appName = brandBundle.GetStringFromName("brandShortName");
  838.     name = updateBundle.formatStringFromName("updateName", 
  839.                                              [appName, this.version], 2);
  840.   }
  841.   this.name = name;
  842. }
  843. Update.prototype = {
  844.   /**
  845.    * See nsIUpdateService.idl
  846.    */
  847.   get patchCount() {
  848.     return this._patches.length;
  849.   },
  850.   
  851.   /**
  852.    * See nsIUpdateService.idl
  853.    */
  854.   getPatchAt: function(index) {
  855.     return this._patches[index];
  856.   },
  857.  
  858.   /**
  859.    * See nsIUpdateService.idl
  860.    * 
  861.    * We use a copy of the state cached on this object in |_state| only when 
  862.    * there is no selected patch, i.e. in the case when we could not load 
  863.    * |.activeUpdate| from the update manager for some reason but still have
  864.    * the update.status file to work with. 
  865.    */
  866.   _state: "",
  867.   set state(state) {
  868.     if (this.selectedPatch)
  869.       this.selectedPatch.state = state;
  870.     this._state = state;
  871.     return state;
  872.   },
  873.   get state() {
  874.     if (this.selectedPatch)
  875.       return this.selectedPatch.state;
  876.     return this._state;
  877.   },
  878.  
  879.   /**
  880.    * See nsIUpdateService.idl
  881.    */
  882.   errorCode: 0,
  883.     
  884.   /**
  885.    * See nsIUpdateService.idl
  886.    */
  887.   get selectedPatch() {
  888.     for (var i = 0; i < this.patchCount; ++i) {
  889.       if (this._patches[i].selected)
  890.         return this._patches[i];
  891.     }
  892.     return null;
  893.   },
  894.   
  895.   /**
  896.    * See nsIUpdateService.idl
  897.    */
  898.   get detailsURL() {
  899.     if (!this._detailsURL) {
  900.       try {
  901.         // Try using a default details URL supplied by the distribution
  902.         // if the update XML does not supply one.
  903.         var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  904.                                   .getService(Components.interfaces.nsIURLFormatter);
  905.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  906.       }
  907.       catch (e) {
  908.       }
  909.     }
  910.     return this._detailsURL || "";
  911.   },
  912.   
  913.   /**
  914.    * See nsIUpdateService.idl
  915.    */
  916.   serialize: function(updates) {
  917.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  918.     update.setAttribute("type", this.type);
  919.     update.setAttribute("name", this.name);
  920.     update.setAttribute("version", this.version);
  921.     update.setAttribute("extensionVersion", this.extensionVersion);
  922.     update.setAttribute("detailsURL", this.detailsURL);
  923.     update.setAttribute("licenseURL", this.licenseURL);
  924.     update.setAttribute("serviceURL", this.serviceURL);
  925.     update.setAttribute("installDate", this.installDate);
  926.     update.setAttribute("statusText", this.statusText);
  927.     update.setAttribute("buildID", this.buildID);
  928.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  929.     update.setAttribute("channel", this.channel);
  930.     updates.documentElement.appendChild(update);
  931.     
  932.     for (var p in this._properties) {
  933.       if (this._properties[p].present)
  934.         update.setAttribute(p, this._properties[p].data);
  935.     }
  936.     
  937.     for (var i = 0; i < this.patchCount; ++i)
  938.       update.appendChild(this.getPatchAt(i).serialize(updates));
  939.     
  940.     return update;
  941.   },
  942.    
  943.   /**
  944.    * A hash of custom properties
  945.    */
  946.   _properties: null,
  947.   
  948.   /**
  949.    * See nsIWritablePropertyBag.idl
  950.    */
  951.   setProperty: function(name, value) {
  952.     this._properties[name] = { data: value, present: true };
  953.   },
  954.   
  955.   /**
  956.    * See nsIWritablePropertyBag.idl
  957.    */
  958.   deleteProperty: function(name) {
  959.     if (name in this._properties)
  960.       this._properties[name].present = false;
  961.     else
  962.       throw Components.results.NS_ERROR_FAILURE;
  963.   },
  964.   
  965.   /**
  966.    * See nsIPropertyBag.idl
  967.    */
  968.   get enumerator() {
  969.     var properties = [];
  970.     for (var p in this._properties)
  971.       properties.push(this._properties[p].data);
  972.     return new ArrayEnumerator(properties);
  973.   },
  974.   
  975.   /**
  976.    * See nsIPropertyBag.idl
  977.    */
  978.   getProperty: function(name) {
  979.     if (name in this._properties &&
  980.         this._properties[name].present)
  981.       return this._properties[name].data;
  982.     throw Components.results.NS_ERROR_FAILURE;
  983.   },
  984.   
  985.   /**
  986.    * See nsISupports.idl
  987.    */
  988.   QueryInterface: function(iid) {
  989.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  990.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  991.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  992.         !iid.equals(Components.interfaces.nsISupports))
  993.       throw Components.results.NS_ERROR_NO_INTERFACE;
  994.     return this;
  995.   }
  996. }; 
  997.  
  998. /**
  999.  * UpdateService
  1000.  * A Service for managing the discovery and installation of software updates.
  1001.  * @constructor
  1002.  */
  1003. function UpdateService() {
  1004.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  1005.                     .getService(Components.interfaces.nsIXULAppInfo)
  1006.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  1007.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  1008.                     .getService(Components.interfaces.nsIPrefBranch2);
  1009.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  1010.                        .getService(Components.interfaces.nsIConsoleService);  
  1011.  
  1012.   // Not all builds have a known ABI
  1013.   try {
  1014.     gABI = gApp.XPCOMABI;
  1015.   }
  1016.   catch (e) {
  1017.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  1018.   }
  1019.  
  1020.   try {
  1021.     var sysInfo = 
  1022.       Components.classes["@mozilla.org/system-info;1"]
  1023.                 .getService(Components.interfaces.nsIPropertyBag2);
  1024.  
  1025.     gOSVersion = encodeURIComponent(sysInfo.getProperty("name") + " " +  
  1026.                                     sysInfo.getProperty("version"));
  1027.   }
  1028.   catch (e) {
  1029.     LOG("UpdateService", "OS Version unknown: updates are not possible.");
  1030.   }
  1031.  
  1032. //@line 1022 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1033.  
  1034.   // Start the update timer only after a profile has been selected so that the
  1035.   // appropriate values for the update check are read from the user's profile.  
  1036.   var os = getObserverService();
  1037.  
  1038.   os.addObserver(this, "profile-after-change", false);
  1039.  
  1040.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid 
  1041.   // shutdown leaks.
  1042.   os.addObserver(this, "xpcom-shutdown", false);
  1043. }
  1044.  
  1045. UpdateService.prototype = {
  1046.   /**
  1047.    * The downloader we are using to download updates. There is only ever one of
  1048.    * these.
  1049.    */
  1050.   _downloader: null,
  1051.  
  1052.   /**
  1053.    * Handle Observer Service notifications
  1054.    * @param   subject
  1055.    *          The subject of the notification
  1056.    * @param   topic
  1057.    *          The notification name
  1058.    * @param   data
  1059.    *          Additional data
  1060.    */
  1061.   observe: function(subject, topic, data) {
  1062.     var os = getObserverService();
  1063.  
  1064.     switch (topic) {
  1065.     case "profile-after-change":
  1066.       os.removeObserver(this, "profile-after-change");
  1067.       this._start();
  1068.       break;
  1069.     case "xpcom-shutdown":
  1070.       os.removeObserver(this, "xpcom-shutdown");
  1071.       
  1072.       // Release Services
  1073.       gApp      = null;
  1074.       gPref     = null;
  1075.       gConsole  = null;
  1076.       break;
  1077.     }
  1078.   },
  1079.   
  1080.   /**
  1081.    * Start the Update Service
  1082.    */
  1083.   _start: function() {
  1084.     // Start logging
  1085.     this._initLoggingPrefs();
  1086.     
  1087.     // Clean up any extant updates
  1088.     this._postUpdateProcessing();
  1089.  
  1090.     // Register a background update check timer
  1091.     var tm = 
  1092.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  1093.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  1094.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1095.     tm.registerTimer("background-update-timer", this, interval);
  1096.  
  1097.     // Resume fetching...
  1098.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1099.                         .getService(Components.interfaces.nsIUpdateManager);
  1100.     var activeUpdate = um.activeUpdate;
  1101.     if (activeUpdate) {
  1102.       var status = this.downloadUpdate(activeUpdate, true);
  1103.       if (status == STATE_NONE)
  1104.         cleanupActiveUpdate();
  1105.     }
  1106.   },
  1107.   
  1108.   /**
  1109.    * Perform post-processing on updates lingering in the updates directory
  1110.    * from a previous browser session - either report install failures (and
  1111.    * optionally attempt to fetch a different version if appropriate) or 
  1112.    * notify the user of install success.
  1113.    */
  1114.   _postUpdateProcessing: function() {
  1115.     // Detect installation failures and notify
  1116.     
  1117.     // Bail out if we don't have appropriate permissions
  1118.     if (!this.canUpdate)
  1119.       return;
  1120.       
  1121.     var status = readStatusFile(getUpdatesDir()); 
  1122.  
  1123.     // Make sure to cleanup after an update that failed for an unknown reason
  1124.     if (status == "null")
  1125.       status = null;
  1126.  
  1127.     var updRootKey = null;
  1128. //@line 1139 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1129.  
  1130.     if (status == STATE_DOWNLOADING) {
  1131.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  1132.     }
  1133.     else if (status != null) {
  1134.       // null status means the update.status file is not present, because either:
  1135.       // 1) no update was performed, and so there's no UI to show
  1136.       // 2) an update was attempted but failed during checking, transfer or 
  1137.       //    verification, and was cleaned up at that point, and UI notifying of
  1138.       //    that error was shown at that stage. 
  1139.       var um = 
  1140.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1141.           getService(Components.interfaces.nsIUpdateManager);
  1142.       var prompter = 
  1143.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1144.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1145.  
  1146.       var shouldCleanup = true;
  1147.       var update = um.activeUpdate;
  1148.       if (!update) {
  1149.         update = new Update(null);
  1150.       }
  1151.       update.state = status;
  1152.       var sbs = 
  1153.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1154.           getService(Components.interfaces.nsIStringBundleService);
  1155.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1156.       if (status == STATE_SUCCEEDED) {
  1157.         update.statusText = bundle.GetStringFromName("installSuccess");
  1158.         
  1159.         // Dig through the update history to find the patch that was just
  1160.         // installed and update its metadata.
  1161.         for (var i = 0; i < um.updateCount; ++i) {
  1162.           var umUpdate = um.getUpdateAt(i);
  1163.           if (umUpdate && umUpdate.version == update.version &&
  1164.                           umUpdate.buildID == update.buildID) {
  1165.             umUpdate.statusText = update.statusText;
  1166.             break;
  1167.           }
  1168.         }
  1169.  
  1170.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1171.         prompter.showUpdateInstalled(update);
  1172. //@line 1183 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1173.         // we need to fix both nsPostUpdateWin.js and 
  1174.         // the uninstaller to work for sunbird
  1175. //@line 1192 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  1176.  
  1177.         // Done with this update. Clean it up.
  1178.         cleanupActiveUpdate(updRootKey);
  1179.       }
  1180.       else {
  1181.         // If we hit an error, then the error code will be included in the
  1182.         // status string following a colon.  If we had an I/O error, then we
  1183.         // assume that the patch is not invalid, and we restage the patch so
  1184.         // that it can be attempted again the next time we restart.
  1185.         var ary = status.split(": ");
  1186.         update.state = ary[0];
  1187.         if (update.state == STATE_FAILED && ary[1]) {
  1188.           update.errorCode = ary[1];
  1189.           if (update.errorCode == WRITE_ERROR) {
  1190.             prompter.showUpdateError(update);
  1191.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1192.             return;
  1193.           }
  1194.         }
  1195.  
  1196.         // Something went wrong with the patch application process.
  1197.         cleanupActiveUpdate();
  1198.  
  1199.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1200.         var oldType = update.selectedPatch ? update.selectedPatch.type 
  1201.                                            : "complete";
  1202.         if (update.selectedPatch && oldType == "partial") {
  1203.           // Partial patch application failed, try downloading the complete
  1204.           // update in the background instead.
  1205.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " + 
  1206.               "failed, downloading Complete Patch and maybe showing UI");
  1207.           var status = this.downloadUpdate(update, true);
  1208.           if (status == STATE_NONE)
  1209.             cleanupActiveUpdate();
  1210.         }
  1211.         else {
  1212.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " + 
  1213.               "only patch failed. Showing error.");
  1214.         }
  1215.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1216.         update.setProperty("patchingFailed", oldType);
  1217.         prompter.showUpdateError(update);
  1218.       }
  1219.     }
  1220.     else {
  1221.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1222.     }
  1223.   },
  1224.  
  1225.   /**
  1226.    * Initialize Logging preferences, formatted like so:
  1227.    *  app.update.log.<moduleName> = <true|false>
  1228.    */
  1229.   _initLoggingPrefs: function() {
  1230.     try {
  1231.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1232.                         .getService(Components.interfaces.nsIPrefService);
  1233.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1234.       var modules = logBranch.getChildList("", { value: 0 });
  1235.  
  1236.       for (var i = 0; i < modules.length; ++i) {
  1237.         if (logBranch.prefHasUserValue(modules[i]))
  1238.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1239.       }
  1240.     }
  1241.     catch (e) {
  1242.     }
  1243.   },
  1244.   
  1245.   /**
  1246.    *
  1247.    */
  1248.   _needsToPromptForUpdate: function(updates) {
  1249.     // First, check for Extension incompatibilities. These trump any preference
  1250.     // settings.
  1251.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  1252.                        .getService(Components.interfaces.nsIExtensionManager);
  1253.     var incompatibleList = { };
  1254.     for (var i = 0; i < updates.length; ++i) {
  1255.       var count = {};
  1256.       em.getIncompatibleItemList(gApp.ID, updates[i].extensionVersion,
  1257.                                  nsIUpdateItem.TYPE_ADDON, false, count);
  1258.       if (count.value > 0)
  1259.         return true;
  1260.     }
  1261.  
  1262.     // Now, inspect user preferences.
  1263.     
  1264.     // No prompt necessary, silently update...
  1265.     return false;
  1266.   },
  1267.   
  1268.   /**
  1269.    * Notified when a timer fires
  1270.    * @param   timer
  1271.    *          The timer that fired
  1272.    */
  1273.   notify: function(timer) {
  1274.     // If a download is in progress, then do nothing.
  1275.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1276.       return;
  1277.  
  1278.     var self = this;
  1279.     var listener = {
  1280.       /**
  1281.        * See nsIUpdateService.idl
  1282.        */
  1283.       onProgress: function(request, position, totalSize) { 
  1284.       },
  1285.       
  1286.       /**
  1287.        * See nsIUpdateService.idl
  1288.        */
  1289.       onCheckComplete: function(request, updates, updateCount) {
  1290.         self._selectAndInstallUpdate(updates);
  1291.       },
  1292.  
  1293.       /**
  1294.        * See nsIUpdateService.idl
  1295.        */
  1296.       onError: function(request, update) { 
  1297.         LOG("Checker", "Error during background update: " + update.statusText);
  1298.       },
  1299.     }
  1300.     this.backgroundChecker.checkForUpdates(listener, false);
  1301.   },
  1302.   
  1303.   /**
  1304.    * Determine whether or not an update requires user confirmation before it
  1305.    * can be installed.
  1306.    * @param   update
  1307.    *          The update to be installed
  1308.    * @returns true if a prompt UI should be shown asking the user if they want
  1309.    *          to install the update, false if the update should just be 
  1310.    *          silently downloaded and installed.
  1311.    */
  1312.   _shouldPrompt: function(update) {
  1313.     // There are two possible outcomes here:
  1314.     // 1. download and install the update automatically
  1315.     // 2. alert the user about the presence of an update before doing anything
  1316.     //
  1317.     // The outcome we follow is determined as follows:
  1318.     // 
  1319.     // Note:  all Major updates require notification and confirmation
  1320.     // 
  1321.     // Update Type      Mode      Incompatible    Outcome
  1322.     // Major            0         Yes or No       Notify and Confirm
  1323.     // Major            1         No              Notify and Confirm
  1324.     // Major            1         Yes             Notify and Confirm
  1325.     // Major            2         Yes or No       Notify and Confirm
  1326.     // Minor            0         Yes or No       Auto Install
  1327.     // Minor            1         No              Auto Install
  1328.     // Minor            1         Yes             Notify and Confirm
  1329.     // Minor            2         No              Auto Install
  1330.     // Minor            2         Yes             Notify and Confirm
  1331.     //
  1332.     // In addition, if there is a license associated with an update, regardless
  1333.     // of type it must be agreed to. 
  1334.     //
  1335.     // If app.update.enabled is set to false, an update check is not performed
  1336.     // at all, and so none of the decision making above is entered into.
  1337.     //
  1338.     if (update.type == "major") {
  1339.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1340.       return true;
  1341.     }
  1342.  
  1343.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1344.     try {
  1345.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1346.     }
  1347.     catch (e) {
  1348.       licenseAccepted = false;
  1349.     }
  1350.     
  1351.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1352.     if (!updateEnabled) {
  1353.       LOG("Checker", "_shouldPrompt: Not prompting because update is " + 
  1354.           "disabled");
  1355.       return false;
  1356.     }
  1357.     
  1358.     // User has turned off automatic download and install
  1359.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1360.     if (!autoEnabled) {
  1361.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1362.       return true;
  1363.     }
  1364.     
  1365.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1366.     case 1:
  1367.       // Mode 1 is do not prompt only if there are no incompatibilities
  1368.       // releases
  1369.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1370.       return !isCompatible(update);
  1371.     case 2:
  1372.       // Mode 2 is do not prompt only if there are no incompatibilities
  1373.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1374.       return !isCompatible(update);
  1375.     }
  1376.     // Mode 0 is do not prompt regardless of incompatibilities
  1377.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1378.         "ignore incompatibilities");
  1379.     return false;
  1380.   },
  1381.   
  1382.   /**
  1383.    * Determine which of the specified updates should be installed.
  1384.    * @param   updates
  1385.    *          An array of available updates
  1386.    */
  1387.   selectUpdate: function(updates) {
  1388.     if (updates.length == 0)
  1389.       return null;
  1390.     
  1391.     // Choose the newest of the available minor and major updates. 
  1392.     var majorUpdate = null, minorUpdate = null;
  1393.     var newestMinor = updates[0], newestMajor = updates[0];
  1394.  
  1395.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1396.                        .getService(Components.interfaces.nsIVersionComparator);
  1397.     for (var i = 0; i < updates.length; ++i) {
  1398.       if (updates[i].type == "major" && 
  1399.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1400.         majorUpdate = newestMajor = updates[i];
  1401.       if (updates[i].type == "minor" && 
  1402.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1403.         minorUpdate = newestMinor = updates[i];
  1404.     }
  1405.  
  1406.     // IMPORTANT
  1407.     // If there's a minor update, always try and fetch that one first, 
  1408.     // otherwise use the newest major update.
  1409.     // selectUpdate() only returns one update.
  1410.     // if major were to trump minor, and we said "never" to the major
  1411.     // we'd never get the minor update, since selectUpdate()
  1412.     // would return the major update that the user said "never" to
  1413.     // (shadowing the important minor update with security fixes)
  1414.     return minorUpdate || majorUpdate;
  1415.   },
  1416.   
  1417.   /**
  1418.    * Determine which of the specified updates should be installed and
  1419.    * begin the download/installation process, optionally prompting the
  1420.    * user for permission if required.
  1421.    * @param   updates
  1422.    *          An array of available updates
  1423.    */
  1424.   _selectAndInstallUpdate: function(updates) {
  1425.     // Don't prompt if there's an active update - the user is already 
  1426.     // aware and is downloading, or performed some user action to prevent
  1427.     // notification.
  1428.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1429.                        .getService(Components.interfaces.nsIUpdateManager);
  1430.     if (um.activeUpdate)
  1431.       return;
  1432.     
  1433.     var update = this.selectUpdate(updates, updates.length);
  1434.     if (!update)
  1435.       return;
  1436.     
  1437.     // check if the user said "never" to this version
  1438.     // this check is done here, and not in selectUpdate() so that
  1439.     // the user can get an upgrade they said "never" to if they
  1440.     // manually do "Check for Updates..."
  1441.     // note, selectUpdate() only returns one update.
  1442.     // but in selectUpdate(), minor updates trump major updates
  1443.     // if major trumps minor, and we said "never" to the major
  1444.     // we'd never see the minor update.
  1445.     // 
  1446.     // note, the never decision should only apply to major updates
  1447.     // see bug #350636 for a scenario where this could potentially
  1448.     // be an issue
  1449.     //
  1450.     // fix for bug #359093
  1451.     // version might one day come back from AUS as an 
  1452.     // arbitrary (and possibly non ascii) string, so we need to encode it
  1453.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + encodeURIComponent(update.version);
  1454.     var never = getPref("getBoolPref", neverPrefName, false);
  1455.     if (never && update.type == "major")
  1456.       return;
  1457.  
  1458.     if (this._shouldPrompt(update))
  1459.       showPromptIfNoIncompatibilities(update);
  1460.     else {
  1461.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1462.       var status = this.downloadUpdate(update, true);
  1463.       if (status == STATE_NONE)
  1464.         cleanupActiveUpdate();
  1465.     }
  1466.   },
  1467.  
  1468.   /**
  1469.    * The Checker used for background update checks.
  1470.    */
  1471.   _backgroundChecker: null,
  1472.   
  1473.   /**
  1474.    * See nsIUpdateService.idl
  1475.    */
  1476.   get backgroundChecker() {
  1477.     if (!this._backgroundChecker) 
  1478.       this._backgroundChecker = new Checker();
  1479.     return this._backgroundChecker;
  1480.   },
  1481.   
  1482.   /**
  1483.    * See nsIUpdateService.idl
  1484.    */
  1485.   get canUpdate() {
  1486.     try {
  1487.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1488.       if (!appDirFile.exists()) {
  1489.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1490.         appDirFile.remove(false);
  1491.       }
  1492.       var updateDir = getUpdatesDir();
  1493.       var upDirFile = updateDir.clone();
  1494.       upDirFile.append(FILE_PERMS_TEST);
  1495.       if (!upDirFile.exists()) {
  1496.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1497.         upDirFile.remove(false);
  1498.       }
  1499.     }
  1500.     catch (e) {
  1501.       // No write privileges to install directory
  1502.       return false;
  1503.     }
  1504.     // If the administrator has locked the app update functionality 
  1505.     // OFF - this is not just a user setting, so disable the manual
  1506.     // UI too.
  1507.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1508.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED))
  1509.       return false;
  1510.  
  1511.     // If we don't know the binary platform we're updating, we can't update.
  1512.     if (!gABI)
  1513.       return false;
  1514.  
  1515.     // If we don't know the OS version we're updating, we can't update.
  1516.     if (!gOSVersion)
  1517.       return false;
  1518.  
  1519.     return true;
  1520.   },
  1521.   
  1522.   /**
  1523.    * See nsIUpdateService.idl
  1524.    */
  1525.   addDownloadListener: function(listener) {
  1526.     if (!this._downloader) {
  1527.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1528.       return;
  1529.     }
  1530.     this._downloader.addDownloadListener(listener);
  1531.   },
  1532.   
  1533.   /**
  1534.    * See nsIUpdateService.idl
  1535.    */
  1536.   removeDownloadListener: function(listener) {
  1537.     if (!this._downloader) {
  1538.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1539.       return;
  1540.     }
  1541.     this._downloader.removeDownloadListener(listener);
  1542.   },
  1543.   
  1544.   /**
  1545.    * See nsIUpdateService.idl
  1546.    */
  1547.   downloadUpdate: function(update, background) {
  1548.     if (!update)
  1549.       throw Components.results.NS_ERROR_NULL_POINTER;
  1550.     if (this.isDownloading) {
  1551.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1552.           background == this._downloader.background) {
  1553.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1554.         return readStatusFile(getUpdatesDir());
  1555.       }
  1556.       this._downloader.cancel();
  1557.     }
  1558.     this._downloader = new Downloader(background);
  1559.     return this._downloader.downloadUpdate(update);
  1560.   },
  1561.   
  1562.   /**
  1563.    * See nsIUpdateService.idl
  1564.    */
  1565.   pauseDownload: function() {
  1566.     if (this.isDownloading)
  1567.       this._downloader.cancel();
  1568.   },
  1569.   
  1570.   /**
  1571.    * See nsIUpdateService.idl
  1572.    */
  1573.   get isDownloading() {
  1574.     return this._downloader && this._downloader.isBusy;
  1575.   },
  1576.   
  1577.   /**
  1578.    * See nsISupports.idl
  1579.    */
  1580.   QueryInterface: function(iid) {
  1581.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1582.         !iid.equals(Components.interfaces.nsITimerCallback) && 
  1583.         !iid.equals(Components.interfaces.nsIObserver) && 
  1584.         !iid.equals(Components.interfaces.nsISupports))
  1585.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1586.     return this;
  1587.   }
  1588. };
  1589.  
  1590. /**
  1591.  * A service to manage active and past updates.
  1592.  * @constructor
  1593.  */
  1594. function UpdateManager() {
  1595.   // Ensure the Active Update file is loaded
  1596.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1597.   if (updates.length > 0)
  1598.     this._activeUpdate = updates[0];
  1599. }
  1600. UpdateManager.prototype = {
  1601.   /**
  1602.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1603.    * objects.
  1604.    */
  1605.   _updates: null,
  1606.   
  1607.   /**
  1608.    * The current actively downloading/installing update, as a nsIUpdate object.
  1609.    */
  1610.   _activeUpdate: null,
  1611.   
  1612.   /**
  1613.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1614.    * @param   file
  1615.    *          A nsIFile for the updates.xml file
  1616.    * @returns The array of nsIUpdate items held in the file.
  1617.    */
  1618.   _loadXMLFileIntoArray: function(file) {
  1619.     if (!file.exists()) {
  1620.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1621.       return [];
  1622.     }
  1623.  
  1624.     var result = [];
  1625.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1626.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1627.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1628.     try {
  1629.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1630.                             .createInstance(Components.interfaces.nsIDOMParser);
  1631.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1632.       
  1633.       var updateCount = doc.documentElement.childNodes.length;
  1634.       for (var i = 0; i < updateCount; ++i) {
  1635.         var updateElement = doc.documentElement.childNodes.item(i);
  1636.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1637.             updateElement.localName != "update")
  1638.           continue;
  1639.  
  1640.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1641.         try {
  1642.           var update = new Update(updateElement);
  1643.         } catch (e) {
  1644.           LOG("UpdateManager", "_loadXMLFileIntoArray: invalid update");
  1645.           continue;
  1646.         }
  1647.         result.push(new Update(updateElement));
  1648.       }
  1649.     }
  1650.     catch (e) {
  1651.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " + 
  1652.           e);
  1653.     }
  1654.     fileStream.close();
  1655.     return result;
  1656.   },
  1657.   
  1658.   /**
  1659.    * Load the update manager, initializing state from state files.
  1660.    */
  1661.   _ensureUpdates: function() {
  1662.     if (!this._updates) {
  1663.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1664.                         [FILE_UPDATES_DB]));
  1665.  
  1666.       // Make sure that any active update is part of our updates list
  1667.       var active = this.activeUpdate;
  1668.       if (active)
  1669.         this._addUpdate(active);
  1670.     }
  1671.   },
  1672.  
  1673.   /**
  1674.    * See nsIUpdateService.idl
  1675.    */
  1676.   getUpdateAt: function(index) {
  1677.     this._ensureUpdates();
  1678.     return this._updates[index];
  1679.   },
  1680.   
  1681.   /**
  1682.    * See nsIUpdateService.idl
  1683.    */
  1684.   get updateCount() {
  1685.     this._ensureUpdates();
  1686.     return this._updates.length;
  1687.   },
  1688.   
  1689.   /**
  1690.    * See nsIUpdateService.idl
  1691.    */
  1692.   get activeUpdate() {
  1693.     if (this._activeUpdate &&
  1694.         this._activeUpdate.channel != getUpdateChannel()) {
  1695.       // User switched channels, clear out any old active updates and remove
  1696.       // partial downloads
  1697.       this._activeUpdate = null;
  1698.       
  1699.       // Destroy the updates directory, since we're done with it.
  1700.       cleanUpUpdatesDir();
  1701.     }
  1702.     return this._activeUpdate;
  1703.   },
  1704.   set activeUpdate(activeUpdate) {
  1705.     this._addUpdate(activeUpdate);
  1706.     this._activeUpdate = activeUpdate;
  1707.     if (!activeUpdate) {
  1708.       // If |activeUpdate| is null, we have updated both lists - the active list
  1709.       // and the history list, so we want to write both files.
  1710.       this.saveUpdates();
  1711.     }
  1712.     else
  1713.       this._writeUpdatesToXMLFile([this._activeUpdate], 
  1714.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1715.     return activeUpdate;
  1716.   },
  1717.   
  1718.   /**
  1719.    * Add an update to the Updates list. If the item already exists in the list,
  1720.    * replace the existing value with the new value.
  1721.    * @param   update
  1722.    *          The nsIUpdate object to add.
  1723.    */
  1724.   _addUpdate: function(update) {
  1725.     if (!update)
  1726.       return;
  1727.     this._ensureUpdates();
  1728.     if (this._updates) {
  1729.       for (var i = 0; i < this._updates.length; ++i) {
  1730.         if (this._updates[i] &&
  1731.             this._updates[i].version == update.version &&
  1732.             this._updates[i].buildID == update.buildID) {
  1733.           // Replace the existing entry with the new value, updating
  1734.           // all metadata.
  1735.           this._updates[i] = update;
  1736.           return;
  1737.         }
  1738.       }
  1739.     }
  1740.     // Otherwise add it to the front of the list.
  1741.     if (update) 
  1742.       this._updates = [update].concat(this._updates);
  1743.   },
  1744.   
  1745.   /**
  1746.    * Serializes an array of updates to an XML file
  1747.    * @param   updates
  1748.    *          An array of nsIUpdate objects
  1749.    * @param   file
  1750.    *          The nsIFile object to serialize to
  1751.    */
  1752.   _writeUpdatesToXMLFile: function(updates, file) {
  1753.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1754.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1755.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1756.     if (!file.exists()) 
  1757.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1758.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1759.     
  1760.     try {
  1761.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1762.                             .createInstance(Components.interfaces.nsIDOMParser);
  1763.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1764.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1765.  
  1766.       for (var i = 0; i < updates.length; ++i) {
  1767.         if (updates[i])
  1768.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1769.       }
  1770.  
  1771.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1772.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1773.       serializer.serializeToStream(doc.documentElement, fos, null);
  1774.     }
  1775.     catch (e) {
  1776.     }
  1777.     
  1778.     closeSafeOutputStream(fos);
  1779.   },
  1780.  
  1781.   /**
  1782.    * See nsIUpdateService.idl
  1783.    */
  1784.   saveUpdates: function() {
  1785.     this._writeUpdatesToXMLFile([this._activeUpdate], 
  1786.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1787.     if (this._updates) {
  1788.       this._writeUpdatesToXMLFile(this._updates.slice(0, 10), 
  1789.                                   getUpdateFile([FILE_UPDATES_DB]));
  1790.     }
  1791.   },
  1792.   
  1793.   /**
  1794.    * See nsISupports.idl
  1795.    */
  1796.   QueryInterface: function(iid) {
  1797.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1798.         !iid.equals(Components.interfaces.nsISupports))
  1799.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1800.     return this;
  1801.   }
  1802. };
  1803.  
  1804.  
  1805. /**
  1806.  * Checker
  1807.  * Checks for new Updates
  1808.  * @constructor
  1809.  */
  1810. function Checker() {
  1811. }
  1812. Checker.prototype = {
  1813.   /**
  1814.    * The XMLHttpRequest object that performs the connection.
  1815.    */
  1816.   _request  : null,
  1817.   
  1818.   /**
  1819.    * The nsIUpdateCheckListener callback
  1820.    */
  1821.   _callback : null,
  1822.   
  1823.   /**
  1824.    * The URL of the update service XML file to connect to that contains details
  1825.    * about available updates.
  1826.    */
  1827.   getUpdateURL: function(force) {
  1828.     this._forced = force;
  1829.  
  1830.     var defaults =
  1831.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1832.         getDefaultBranch(null);
  1833.  
  1834.     // Use the override URL if specified.
  1835.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1836.  
  1837.     // Otherwise, construct the update URL from component parts.
  1838.     if (!url) {
  1839.       try {
  1840.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1841.       } catch (e) {
  1842.       }
  1843.     }
  1844.  
  1845.     if (!url || url == "") {
  1846.       LOG("Checker", "Update URL not defined");
  1847.       return null;
  1848.     }
  1849.  
  1850.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1851.     url = url.replace(/%VERSION%/g, gApp.version);
  1852.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1853.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1854.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  1855.     url = url.replace(/%LOCALE%/g, getLocale());
  1856.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1857.     url = url.replace(/\+/g, "%2B");
  1858.  
  1859.     if (force)
  1860.     url += "?force=1"
  1861.  
  1862.     LOG("Checker", "update url: " + url);
  1863.     return url;
  1864.   },
  1865.   
  1866.   /**
  1867.    * See nsIUpdateService.idl
  1868.    */
  1869.   checkForUpdates: function(listener, force) {
  1870.     if (!listener)
  1871.       throw Components.results.NS_ERROR_NULL_POINTER;
  1872.       
  1873.     if (!this.getUpdateURL(force) || (!this.enabled && !force))
  1874.       return;
  1875.       
  1876.     this._request = 
  1877.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1878.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1879.     this._request.open("GET", this.getUpdateURL(force), true);
  1880.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1881.     this._request.overrideMimeType("text/xml");
  1882.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1883.     
  1884.     var self = this;
  1885.     this._request.onerror     = function(event) { self.onError(event);    };
  1886.     this._request.onload      = function(event) { self.onLoad(event);     };
  1887.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1888.  
  1889.     LOG("Checker", "checkForUpdates: sending request to " + this.getUpdateURL(force));
  1890.     this._request.send(null);
  1891.     
  1892.     this._callback = listener;
  1893.   },
  1894.   
  1895.   /**
  1896.    * When progress associated with the XMLHttpRequest is received.
  1897.    * @param   event
  1898.    *          The nsIDOMLSProgressEvent for the load.
  1899.    */
  1900.   onProgress: function(event) {
  1901.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1902.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1903.   },
  1904.   
  1905.   /**
  1906.    * Returns an array of nsIUpdate objects discovered by the update check.
  1907.    */
  1908.   get _updates() {
  1909.     var updatesElement = this._request.responseXML.documentElement;
  1910.     if (!updatesElement) {
  1911.       LOG("Checker", "get_updates: empty updates document?!");
  1912.       return [];
  1913.     }
  1914.  
  1915.     if (updatesElement.nodeName != "updates") {
  1916.       LOG("Checker", "get_updates: unexpected node name!");
  1917.       throw "";
  1918.     }
  1919.     
  1920.     var updates = [];
  1921.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1922.       var updateElement = updatesElement.childNodes.item(i);
  1923.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1924.           updateElement.localName != "update")
  1925.         continue;
  1926.  
  1927.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1928.       try {
  1929.         var update = new Update(updateElement);
  1930.       } catch (e) {
  1931.         LOG("Checker", "Invalid <update/>, ignoring...");
  1932.         continue;
  1933.       }
  1934.       update.serviceURL = this.getUpdateURL(this._forced);
  1935.       update.channel = getUpdateChannel();
  1936.       updates.push(update);
  1937.     }
  1938.  
  1939.     return updates;
  1940.   },
  1941.   
  1942.   /**
  1943.    * The XMLHttpRequest succeeded and the document was loaded.
  1944.    * @param   event
  1945.    *          The nsIDOMLSEvent for the load
  1946.    */
  1947.   onLoad: function(event) {
  1948.     LOG("Checker", "onLoad: request completed downloading document");
  1949.     
  1950.     try {
  1951.       checkCert(this._request.channel);
  1952.  
  1953.       // Analyze the resulting DOM and determine the set of updates to install
  1954.       var updates = this._updates;
  1955.       
  1956.       LOG("Checker", "Updates available: " + updates.length);
  1957.       
  1958.       // ... and tell the Update Service about what we discovered.
  1959.       this._callback.onCheckComplete(event.target, updates, updates.length);
  1960.     }
  1961.     catch (e) {
  1962.       LOG("Checker", "There was a problem with the update service URL specified, " + 
  1963.           "either the XML file was malformed or it does not exist at the location " + 
  1964.           "specified. Exception: " + e);
  1965.       var update = new Update(null);
  1966.       update.statusText = getStatusTextFromCode(404, 404);
  1967.       this._callback.onError(event.target, update);
  1968.     }
  1969.  
  1970.     this._request = null;
  1971.   },
  1972.   
  1973.   /**
  1974.    * There was an error of some kind during the XMLHttpRequest
  1975.    * @param   event
  1976.    *          The nsIDOMLSEvent for the load
  1977.    */
  1978.   onError: function(event) {
  1979.     LOG("Checker", "onError: error during load");
  1980.     
  1981.     var request = event.target;
  1982.     try {
  1983.       var status = request.status;
  1984.     }
  1985.     catch (e) {
  1986.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  1987.       status = req.status;
  1988.     }
  1989.     
  1990.     // If we can't find an error string specific to this status code, 
  1991.     // just use the 200 message from above, which means everything 
  1992.     // "looks" fine but there was probably an XML error or a bogus file.
  1993.     var update = new Update(null);
  1994.     update.statusText = getStatusTextFromCode(status, 200);
  1995.     this._callback.onError(request, update);
  1996.  
  1997.     this._request = null;
  1998.   },
  1999.   
  2000.   /**
  2001.    * Whether or not we are allowed to do update checking.
  2002.    */
  2003.   _enabled: true,
  2004.   
  2005.   /**
  2006.    * See nsIUpdateService.idl
  2007.    */
  2008.   get enabled() {
  2009.     var aus = 
  2010.         Components.classes["@mozilla.org/updates/update-service;1"].
  2011.         getService(Components.interfaces.nsIApplicationUpdateService);
  2012.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) && 
  2013.                   aus.canUpdate && this._enabled;
  2014.     return enabled;
  2015.   },
  2016.   
  2017.   /**
  2018.    * See nsIUpdateService.idl
  2019.    */
  2020.   stopChecking: function(duration) {
  2021.     // Always stop the current check
  2022.     if (this._request)
  2023.       this._request.abort();
  2024.     
  2025.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  2026.     switch (duration) {
  2027.     case nsIUpdateChecker.CURRENT_SESSION:
  2028.       this._enabled = false;
  2029.       break;
  2030.     case nsIUpdateChecker.ANY_CHECKS:
  2031.       this._enabled = false;
  2032.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2033.       break;
  2034.     }
  2035.   },
  2036.   
  2037.   /**
  2038.    * See nsISupports.idl
  2039.    */
  2040.   QueryInterface: function(iid) {
  2041.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  2042.         !iid.equals(Components.interfaces.nsISupports))
  2043.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2044.     return this;
  2045.   }
  2046. };
  2047.  
  2048. /**
  2049.  * Manages the download of updates
  2050.  * @param   background
  2051.  *          Whether or not this downloader is operating in background
  2052.  *          update mode. 
  2053.  * @constructor
  2054.  */
  2055. function Downloader(background) {
  2056.   this.background = background;
  2057. }
  2058. Downloader.prototype = {
  2059.   /**
  2060.    * The nsIUpdatePatch that we are downloading
  2061.    */
  2062.   _patch: null,
  2063.   
  2064.   /**
  2065.    * The nsIUpdate that we are downloading
  2066.    */
  2067.   _update: null,
  2068.   
  2069.   /**
  2070.    * The nsIIncrementalDownload object handling the download
  2071.    */
  2072.   _request: null,
  2073.  
  2074.   /**
  2075.    * Whether or not the update being downloaded is a complete replacement of
  2076.    * the user's existing installation or a patch representing the difference
  2077.    * between the new version and the previous version.
  2078.    */
  2079.   isCompleteUpdate: null,
  2080.  
  2081.   /**
  2082.    * Cancels the active download.
  2083.    */  
  2084.   cancel: function() {
  2085.     if (this._request && 
  2086.         this._request instanceof Components.interfaces.nsIRequest) {
  2087.       const NS_BINDING_ABORTED = 0x804b0002;
  2088.       this._request.cancel(NS_BINDING_ABORTED);
  2089.     }
  2090.   },
  2091.  
  2092.   /**
  2093.    * Whether or not a patch has been downloaded and staged for installation.
  2094.    */
  2095.   get patchIsStaged() {
  2096.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2097.   },
  2098.  
  2099.   /**
  2100.    * Verify the downloaded file.  We assume that the download is complete at
  2101.    * this point.
  2102.    */
  2103.   _verifyDownload: function() {
  2104.     if (!this._request)
  2105.       return false;
  2106.  
  2107.     var destination = this._request.destination;
  2108.  
  2109.     // Ensure that the file size matches the expected file size.
  2110.     if (destination.fileSize != this._patch.size)
  2111.       return false;
  2112.  
  2113.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2114.         createInstance(nsIFileInputStream);
  2115.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2116.  
  2117.     try {
  2118.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2119.           createInstance(nsICryptoHash);
  2120.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2121.       if (hashFunction == undefined)
  2122.         throw Components.results.NS_ERROR_UNEXPECTED;
  2123.       hash.init(hashFunction);
  2124.       hash.updateFromStream(fileStream, -1);
  2125.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2126.       // encoded binary (such as what is typically output by programs like
  2127.       // sha1sum).  In the future, this may change to base64 depending on how
  2128.       // we choose to compute these hashes.
  2129.       digest = binaryToHex(hash.finish(false));
  2130.     } catch (e) {
  2131.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2132.       digest = "";
  2133.     }
  2134.  
  2135.     fileStream.close();
  2136.  
  2137.     return digest == this._patch.hashValue.toLowerCase();
  2138.   },
  2139.  
  2140.   /**
  2141.    * Select the patch to use given the current state of updateDir and the given
  2142.    * set of update patches.
  2143.    * @param   update
  2144.    *          A nsIUpdate object to select a patch from
  2145.    * @param   updateDir
  2146.    *          A nsIFile representing the update directory
  2147.    * @returns A nsIUpdatePatch object to download
  2148.    */
  2149.   _selectPatch: function(update, updateDir) {
  2150.     // Given an update to download, we will always try to download the patch
  2151.     // for a partial update over the patch for a full update.
  2152.  
  2153.     /**
  2154.      * Return the first UpdatePatch with the given type.
  2155.      * @param   type
  2156.      *          The type of the patch ("complete" or "partial")
  2157.      * @returns A nsIUpdatePatch object matching the type specified
  2158.      */
  2159.     function getPatchOfType(type) {
  2160.       for (var i = 0; i < update.patchCount; ++i) {
  2161.         var patch = update.getPatchAt(i);
  2162.         if (patch && patch.type == type)
  2163.           return patch;
  2164.       }
  2165.       return null;
  2166.     }
  2167.  
  2168.     // Look to see if any of the patches in the Update object has been
  2169.     // pre-selected for download, otherwise we must figure out which one
  2170.     // to select ourselves. 
  2171.     var selectedPatch = update.selectedPatch;
  2172.     
  2173.     var state = readStatusFile(updateDir);
  2174.  
  2175.     // If this is a patch that we know about, then select it.  If it is a patch
  2176.     // that we do not know about, then remove it and use our default logic.
  2177.     var useComplete = false;
  2178.     if (selectedPatch) {
  2179.       LOG("Downloader", "found existing patch [state="+state+"]");
  2180.       switch (state) {
  2181.       case STATE_DOWNLOADING: 
  2182.         LOG("Downloader", "resuming download");
  2183.         return selectedPatch;
  2184.       case STATE_PENDING:
  2185.         LOG("Downloader", "already downloaded and staged");
  2186.         return null;
  2187.       default:
  2188.         // Something went wrong when we tried to apply the previous patch.
  2189.         // Try the complete patch next time.
  2190.         if (update && selectedPatch.type == "partial") {
  2191.           useComplete = true;
  2192.         } else {
  2193.           // This is a pretty fatal error.  Just bail.
  2194.           LOG("Downloader", "failed to apply complete patch!");
  2195.           writeStatusFile(updateDir, STATE_NONE);
  2196.           return null;
  2197.         }
  2198.       }
  2199.  
  2200.       selectedPatch = null;
  2201.     }
  2202.     
  2203.     // If we were not able to discover an update from a previous download, we 
  2204.     // select the best patch from the given set.
  2205.     var partialPatch = getPatchOfType("partial");
  2206.     if (!useComplete)
  2207.       selectedPatch = partialPatch;
  2208.     if (!selectedPatch) {
  2209.       if (partialPatch)
  2210.         partialPatch.selected = false;
  2211.       selectedPatch = getPatchOfType("complete");
  2212.     }
  2213.  
  2214.     // Restore the updateDir since we may have deleted it.
  2215.     updateDir = getUpdatesDir();
  2216.  
  2217.     // if update only contains a partial patch, selectedPatch == null here if
  2218.     // the partial patch has been attempted and fails and we're trying to get a
  2219.     // complete patch
  2220.     if (selectedPatch)    
  2221.       selectedPatch.selected = true;
  2222.  
  2223.     update.isCompleteUpdate = useComplete;
  2224.     
  2225.     // Reset the Active Update object on the Update Manager and flush the
  2226.     // Active Update DB. 
  2227.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2228.                        .getService(Components.interfaces.nsIUpdateManager);
  2229.     um.activeUpdate = update;
  2230.  
  2231.     return selectedPatch;
  2232.   },
  2233.  
  2234.   /**
  2235.    * Whether or not we are currently downloading something.
  2236.    */
  2237.   get isBusy() {
  2238.     return this._request != null;
  2239.   },
  2240.   
  2241.   /**
  2242.    * Download and stage the given update.
  2243.    * @param   update
  2244.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2245.    */
  2246.   downloadUpdate: function(update) {
  2247.     if (!update)
  2248.       throw Components.results.NS_ERROR_NULL_POINTER;
  2249.     
  2250.     var updateDir = getUpdatesDir();
  2251.  
  2252.     this._update = update;
  2253.  
  2254.     // This function may return null, which indicates that there are no patches
  2255.     // to download.
  2256.     this._patch = this._selectPatch(update, updateDir);
  2257.     if (!this._patch) {
  2258.       LOG("Downloader", "no patch to download");
  2259.       return readStatusFile(updateDir);
  2260.     }
  2261.     this.isCompleteUpdate = this._patch.type == "complete";
  2262.  
  2263.     var patchFile = updateDir.clone();
  2264.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2265.  
  2266.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2267.         getService(Components.interfaces.nsIIOService);
  2268.     var uri = ios.newURI(this._patch.URL, null, null);
  2269.  
  2270.     this._request =
  2271.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2272.         createInstance(nsIIncrementalDownload);
  2273.  
  2274.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " + 
  2275.         patchFile.path);
  2276.  
  2277.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2278.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2279.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2280.     this._request.start(this, null);
  2281.  
  2282.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2283.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2284.     this._patch.state = STATE_DOWNLOADING;
  2285.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2286.                        .getService(Components.interfaces.nsIUpdateManager);
  2287.     um.saveUpdates();
  2288.     return STATE_DOWNLOADING;
  2289.   },
  2290.   
  2291.   /**
  2292.    * An array of download listeners to notify when we receive 
  2293.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2294.    */
  2295.   _listeners: [],
  2296.  
  2297.   /** 
  2298.    * Adds a listener to the download process
  2299.    * @param   listener
  2300.    *          A download listener, implementing nsIRequestObserver and
  2301.    *          nsIProgressEventSink
  2302.    */
  2303.   addDownloadListener: function(listener) {
  2304.     for (var i = 0; i < this._listeners.length; ++i) {
  2305.       if (this._listeners[i] == listener)
  2306.         return;
  2307.     }
  2308.     this._listeners.push(listener);
  2309.   },
  2310.   
  2311.   /** 
  2312.    * Removes a download listener
  2313.    * @param   listener
  2314.    *          The listener to remove.
  2315.    */
  2316.   removeDownloadListener: function(listener) {
  2317.     for (var i = 0; i < this._listeners.length; ++i) {
  2318.       if (this._listeners[i] == listener) {
  2319.         this._listeners.splice(i, 1);
  2320.         return;
  2321.       }
  2322.     }
  2323.   },
  2324.   
  2325.   /**
  2326.    * When the async request begins
  2327.    * @param   request
  2328.    *          The nsIRequest object for the transfer
  2329.    * @param   context
  2330.    *          Additional data
  2331.    */
  2332.   onStartRequest: function(request, context) {
  2333.     request.QueryInterface(nsIIncrementalDownload);
  2334.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2335.     
  2336.     var listenerCount = this._listeners.length;
  2337.     for (var i = 0; i < listenerCount; ++i)
  2338.       this._listeners[i].onStartRequest(request, context);
  2339.   },
  2340.   
  2341.   /** 
  2342.    * When new data has been downloaded
  2343.    * @param   request
  2344.    *          The nsIRequest object for the transfer
  2345.    * @param   context
  2346.    *          Additional data
  2347.    * @param   progress
  2348.    *          The current number of bytes transferred
  2349.    * @param   maxProgress
  2350.    *          The total number of bytes that must be transferred
  2351.    */
  2352.   onProgress: function(request, context, progress, maxProgress) {
  2353.     request.QueryInterface(nsIIncrementalDownload);
  2354.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2355.     
  2356.     var listenerCount = this._listeners.length;
  2357.     for (var i = 0; i < listenerCount; ++i) {
  2358.       var listener = this._listeners[i];
  2359.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2360.         listener.onProgress(request, context, progress, maxProgress);
  2361.     }
  2362.   },
  2363.   
  2364.   /** 
  2365.    * When we have new status text
  2366.    * @param   request
  2367.    *          The nsIRequest object for the transfer
  2368.    * @param   context
  2369.    *          Additional data
  2370.    * @param   status
  2371.    *          A status code
  2372.    * @param   statusText
  2373.    *          Human readable version of |status|
  2374.    */
  2375.   onStatus: function(request, context, status, statusText) {
  2376.     request.QueryInterface(nsIIncrementalDownload);
  2377.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2378.     var listenerCount = this._listeners.length;
  2379.     for (var i = 0; i < listenerCount; ++i) {
  2380.       var listener = this._listeners[i];
  2381.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2382.         listener.onStatus(request, context, status, statusText);
  2383.     }
  2384.   },
  2385.   
  2386.   /** 
  2387.    * When data transfer ceases
  2388.    * @param   request
  2389.    *          The nsIRequest object for the transfer
  2390.    * @param   context
  2391.    *          Additional data
  2392.    * @param   status
  2393.    *          Status code containing the reason for the cessation.
  2394.    */
  2395.   onStopRequest: function(request, context, status) {
  2396.     request.QueryInterface(nsIIncrementalDownload);
  2397.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2398.  
  2399.     var state = this._patch.state;
  2400.     var shouldShowPrompt = false;
  2401.     var deleteActiveUpdate = false;
  2402.     const NS_BINDING_ABORTED = 0x804b0002;
  2403.     const NS_ERROR_ABORT = 0x80004004;
  2404.     if (Components.isSuccessCode(status)) {
  2405.       var sbs = 
  2406.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  2407.           getService(Components.interfaces.nsIStringBundleService);
  2408.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2409.       if (this._verifyDownload()) {
  2410.         state = STATE_PENDING;
  2411.         
  2412.         // We only need to explicitly show the prompt if this is a backround
  2413.         // download, since otherwise some kind of UI is already visible and 
  2414.         // that UI will notify. 
  2415.         if (this.background)
  2416.           shouldShowPrompt = true;
  2417.         
  2418.         // Tell the updater.exe we're ready to apply.
  2419.         writeStatusFile(getUpdatesDir(), state);
  2420.         this._update.installDate = (new Date()).getTime();
  2421.         this._update.statusText = updateStrings.
  2422.           GetStringFromName("installPending");
  2423.       } else {
  2424.         LOG("Downloader", "onStopRequest: download verification failed");
  2425.         state = STATE_DOWNLOAD_FAILED;
  2426.         
  2427.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2428.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2429.         this._update.statusText = updateStrings.
  2430.           formatStringFromName("verificationError", [brandShortName], 1);
  2431.         
  2432.         // TODO: use more informative error code here
  2433.         status = Components.results.NS_ERROR_UNEXPECTED;
  2434.         
  2435.         var message = getStatusTextFromCode("verification_failed", 
  2436.           "verification_failed");
  2437.         this._update.statusText = message;
  2438.         
  2439.         if (this._update.isCompleteUpdate)
  2440.           deleteActiveUpdate = true;
  2441.  
  2442.         // Destroy the updates directory, since we're done with it.
  2443.         cleanUpUpdatesDir();
  2444.       }
  2445.     }
  2446.     else if (status != NS_BINDING_ABORTED &&
  2447.              status != NS_ERROR_ABORT) {
  2448.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2449.       // Some sort of other failure, log this in the |statusText| property
  2450.       state = STATE_DOWNLOAD_FAILED;
  2451.       
  2452.       // XXXben - if |request| (The Incremental Download) provided a means
  2453.       // for accessing the http channel we could do more here.
  2454.       
  2455.       const NS_BINDING_FAILED = 2152398849;
  2456.       this._update.statusText = getStatusTextFromCode(status, 
  2457.         NS_BINDING_FAILED);
  2458.       
  2459.       // Destroy the updates directory, since we're done with it.
  2460.       cleanUpUpdatesDir();
  2461.       
  2462.       deleteActiveUpdate = true;
  2463.     }
  2464.     LOG("Downloader", "Setting state to: " + state);
  2465.     this._patch.state = state;
  2466.     var um = 
  2467.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2468.         getService(Components.interfaces.nsIUpdateManager);
  2469.     if (deleteActiveUpdate) {
  2470.       this._update.installDate = (new Date()).getTime();
  2471.       um.activeUpdate = null;
  2472.     }
  2473.     um.saveUpdates();
  2474.     
  2475.     var listenerCount = this._listeners.length;
  2476.     for (var i = 0; i < listenerCount; ++i)
  2477.       this._listeners[i].onStopRequest(request, context, status);
  2478.  
  2479.     this._request = null;
  2480.     
  2481.     if (state == STATE_DOWNLOAD_FAILED) {
  2482.       if (!this._update.isCompleteUpdate) {
  2483.         var allFailed = true;
  2484.   
  2485.         // If we were downloading a patch and the patch verification phase 
  2486.         // failed, log this and then commence downloading the complete update.
  2487.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2488.         this._update.isCompleteUpdate = true;
  2489.         var status = this.downloadUpdate(this._update);
  2490.  
  2491.         if (status == STATE_NONE) {
  2492.           cleanupActiveUpdate();
  2493.         } else {
  2494.           allFailed = false;
  2495.         }
  2496.         // This will reset the |.state| property on this._update if a new 
  2497.         // download initiates.
  2498.       }
  2499.     
  2500.       // if we still fail after trying a complete download, give up completely
  2501.       if (allFailed) {
  2502.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2503.         // ...
  2504.         
  2505.         // If this was ever a foreground download, and now there is no UI active
  2506.         // (e.g. because the user closed the download window) and there was an
  2507.         // error, we must notify now. Otherwise we can keep the failure to 
  2508.         // ourselves since the user won't be expecting it. 
  2509.         try {
  2510.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2511.           var fgdl = this._update.getProperty("foregroundDownload");
  2512.         }
  2513.         catch (e) {
  2514.         }
  2515.       
  2516.         if (fgdl == "true") {
  2517.           var prompter = 
  2518.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2519.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2520.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2521.           this._update.setProperty("downloadFailed", "true");
  2522.           prompter.showUpdateError(this._update);
  2523.         }
  2524.       }
  2525.  
  2526.       // the complete download succeeded or total failure was handled, so exit
  2527.       return;
  2528.     }
  2529.  
  2530.     // Do this after *everything* else, since it will likely cause the app 
  2531.     // to shut down. 
  2532.     if (shouldShowPrompt) {
  2533.       // Notify the user that an update has been downloaded and is ready for 
  2534.       // installation (i.e. that they should restart the application). We do
  2535.       // not notify on failed update attempts.
  2536.       var prompter = 
  2537.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2538.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2539.       prompter.showUpdateDownloaded(this._update);
  2540.     }
  2541.   },
  2542.  
  2543.   /**
  2544.    * See nsIInterfaceRequestor.idl
  2545.    */
  2546.   getInterface: function(iid) {
  2547.     // The network request may require proxy authentication, so provide the
  2548.     // default nsIAuthPrompt if requested.
  2549.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2550.       var prompt =
  2551.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2552.           createInstance();
  2553.       return prompt.QueryInterface(iid);
  2554.     }
  2555.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2556.   },
  2557.    
  2558.   /**
  2559.    * See nsISupports.idl
  2560.    */
  2561.   QueryInterface: function(iid) {
  2562.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2563.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2564.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2565.         !iid.equals(Components.interfaces.nsISupports))
  2566.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2567.     return this;
  2568.   }
  2569. };
  2570.  
  2571. /**
  2572.  * A manager for update check timers. Manages timers that fire over long 
  2573.  * periods of time (e.g. days, weeks).
  2574.  * @constructor
  2575.  */
  2576. function TimerManager() {
  2577.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2578.  
  2579.   const nsITimer = Components.interfaces.nsITimer;
  2580.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2581.                           .createInstance(nsITimer);
  2582.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2583.   this._timer.initWithCallback(this, timerInterval, 
  2584.                                nsITimer.TYPE_REPEATING_SLACK);
  2585. }
  2586. TimerManager.prototype = {
  2587.   /**
  2588.    * See nsIObserver.idl
  2589.    */
  2590.   observe: function(subject, topic, data) {
  2591.     if (topic == "xpcom-shutdown") {
  2592.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2593.  
  2594.       // Release everything we hold onto. 
  2595.       for (var timerID in this._timers)
  2596.         delete this._timers[timerID];
  2597.       this._timer = null;
  2598.       this._timers = null;
  2599.     }
  2600.   },
  2601.  
  2602.   /**
  2603.    * The Checker Timer
  2604.    */
  2605.   _timer: null,
  2606.   
  2607.   /**
  2608.    * The set of registered timers.
  2609.    */
  2610.   _timers: { },
  2611.   
  2612.   /**
  2613.    * Called when the checking timer fires.
  2614.    * @param   timer
  2615.    *          The checking timer that fired. 
  2616.    */
  2617.   notify: function(timer) {
  2618.     for (var timerID in this._timers) {
  2619.       var timerData = this._timers[timerID];
  2620.       var lastUpdateTime = timerData.lastUpdateTime;
  2621.       var now = Math.round(Date.now() / 1000);
  2622.     
  2623.       // Fudge the lastUpdateTime by some random increment of the update 
  2624.       // check interval (e.g. some random slice of 10 minutes) so that when
  2625.       // the time comes to check, we offset each client request by a random
  2626.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2627.       // whereas app.update.lastUpdateTime is in seconds
  2628.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2629.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2630.  
  2631.       if ((now - lastUpdateTime) > timerData.interval &&
  2632.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2633.         timerData.callback.notify(timer);
  2634.         timerData.lastUpdateTime = now;
  2635.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2636.         gPref.setIntPref(preference, now);
  2637.       }
  2638.     }
  2639.   },
  2640.   
  2641.   /**
  2642.    * See nsIUpdateService.idl
  2643.    */
  2644.   registerTimer: function(id, callback, interval) {
  2645.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2646.     var now = Math.round(Date.now() / 1000);
  2647.     var lastUpdateTime = null;
  2648.     if (gPref.prefHasUserValue(preference)) {
  2649.       lastUpdateTime = gPref.getIntPref(preference);
  2650.     } else {
  2651.       gPref.setIntPref(preference, now);
  2652.       lastUpdateTime = now;
  2653.     }
  2654.     this._timers[id] = { callback       : callback, 
  2655.                          interval       : interval,
  2656.                          lastUpdateTime : lastUpdateTime }; 
  2657.   },
  2658.  
  2659.   /**
  2660.    * See nsISupports.idl
  2661.    */
  2662.   QueryInterface: function(iid) {
  2663.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2664.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2665.         !iid.equals(Components.interfaces.nsIObserver) &&
  2666.         !iid.equals(Components.interfaces.nsISupports))
  2667.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2668.     return this;
  2669.   }
  2670. };
  2671.  
  2672. //@line 2689 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2673. /**
  2674.  * UpdatePrompt
  2675.  * An object which can prompt the user with information about updates, request
  2676.  * action, etc. Embedding clients can override this component with one that 
  2677.  * invokes a native front end. 
  2678.  * @constructor
  2679.  */
  2680. function UpdatePrompt() {
  2681. }
  2682. UpdatePrompt.prototype = {
  2683.   /**
  2684.    * See nsIUpdateService.idl
  2685.    */
  2686.   checkForUpdates: function() {
  2687.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2688.                  null, null);
  2689.   },
  2690.     
  2691.   /**
  2692.    * See nsIUpdateService.idl
  2693.    */
  2694.   showUpdateAvailable: function(update) {
  2695.     if (this._enabled) {
  2696.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2697.                    "updatesavailable", update);
  2698.     }
  2699.   },
  2700.   
  2701.   /**
  2702.    * See nsIUpdateService.idl
  2703.    */
  2704.   showUpdateDownloaded: function(update) {
  2705.     if (this._enabled) {
  2706.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2707.                    "finishedBackground", update);
  2708.     }
  2709.   },
  2710.   
  2711.   /**
  2712.    * See nsIUpdateService.idl
  2713.    */
  2714.   showUpdateInstalled: function(update) {
  2715.     var showUpdateInstalledUI = getPref("getBoolPref", 
  2716.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2717.     if (this._enabled && showUpdateInstalledUI) {
  2718.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2719.                    "installed", update);
  2720.     }
  2721.   },
  2722.   
  2723.   /**
  2724.    * See nsIUpdateService.idl
  2725.    */
  2726.   showUpdateError: function(update) {
  2727.     if (this._enabled) {
  2728.       // In some cases, we want to just show a simple alert dialog:
  2729.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2730.         var sbs = 
  2731.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2732.             getService(Components.interfaces.nsIStringBundleService);
  2733.         var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2734.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2735.         var text = updateBundle.formatStringFromName("updaterIOErrorMsg",
  2736.                                                      [gApp.name, gApp.name], 2);
  2737.         var ww =
  2738.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2739.             getService(Components.interfaces.nsIWindowWatcher);
  2740.         ww.getNewPrompter(null).alert(title, text);
  2741.       } else {
  2742.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2743.                      "errors", update);
  2744.       }
  2745.     }
  2746.   },
  2747.   
  2748.   /**
  2749.    * See nsIUpdateService.idl
  2750.    */
  2751.   showUpdateHistory: function(parent) {
  2752.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History", 
  2753.                  null, null);
  2754.   },
  2755.   
  2756.   /**
  2757.    * Whether or not we are enabled (i.e. not in Silent mode)
  2758.    */
  2759.   get _enabled() {
  2760.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2761.   },
  2762.   
  2763.   /**
  2764.    * Show the Update Checking UI
  2765.    * @param   parent
  2766.    *          A parent window, can be null
  2767.    * @param   uri
  2768.    *          The URI string of the dialog to show
  2769.    * @param   name
  2770.    *          The Window Name of the dialog to show, in case it is already open
  2771.    *          and can merely be focused
  2772.    * @param   page
  2773.    *          The page of the wizard to be displayed, if one is already open.
  2774.    * @param   update
  2775.    *          An update to pass to the UI in the window arguments. 
  2776.    *          Can be null
  2777.    */
  2778.   _showUI: function(parent, uri, features, name, page, update) {
  2779.     var ary = null;
  2780.     if (update) {
  2781.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2782.                       .createInstance(Components.interfaces.nsISupportsArray);
  2783.       ary.AppendElement(update);
  2784.     }
  2785.       
  2786.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2787.                        .getService(Components.interfaces.nsIWindowMediator);
  2788.     var win = wm.getMostRecentWindow(name);
  2789.     if (win) {
  2790.       if (page && "setCurrentPage" in win)
  2791.         win.setCurrentPage(page);
  2792.       win.focus();
  2793.     }
  2794.     else {
  2795.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2796.       if (features)
  2797.         openFeatures += "," + features;
  2798.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2799.                          .getService(Components.interfaces.nsIWindowWatcher);
  2800.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2801.     }
  2802.   },
  2803.   
  2804.   /**
  2805.    * See nsISupports.idl
  2806.    */
  2807.   QueryInterface: function(iid) {
  2808.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2809.         !iid.equals(Components.interfaces.nsISupports))
  2810.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2811.     return this;
  2812.   }
  2813. };
  2814. //@line 2831 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2815.  
  2816. var gModule = {
  2817.   registerSelf: function(componentManager, fileSpec, location, type) {
  2818.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  2819.     
  2820.     for (var key in this._objects) {
  2821.       var obj = this._objects[key];
  2822.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  2823.                                                fileSpec, location, type);
  2824.     }
  2825.  
  2826.     // Make the Update Service a startup observer
  2827.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2828.                                     .getService(Components.interfaces.nsICategoryManager);
  2829.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  2830.                                      "service," + this._objects.service.contractID, 
  2831.                                      true, true, null);
  2832.   },
  2833.   
  2834.   getClassObject: function(componentManager, cid, iid) {
  2835.     if (!iid.equals(Components.interfaces.nsIFactory))
  2836.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  2837.  
  2838.     for (var key in this._objects) {
  2839.       if (cid.equals(this._objects[key].CID))
  2840.         return this._objects[key].factory;
  2841.     }
  2842.     
  2843.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2844.   },
  2845.   
  2846.   _objects: {
  2847.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  2848.                contractID : "@mozilla.org/updates/update-service;1",
  2849.                className  : "Update Service",
  2850.                factory    : makeFactory(UpdateService)
  2851.              },
  2852.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2853.                contractID : "@mozilla.org/updates/update-checker;1",
  2854.                className  : "Update Checker",
  2855.                factory    : makeFactory(Checker)
  2856.              },
  2857. //@line 2874 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2858.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  2859.                contractID : "@mozilla.org/updates/update-prompt;1",
  2860.                className  : "Update Prompt",
  2861.                factory    : makeFactory(UpdatePrompt)
  2862.              },
  2863. //@line 2880 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2864.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2865.                contractID : "@mozilla.org/updates/timer-manager;1",
  2866.                className  : "Timer Manager",
  2867.                factory    : makeFactory(TimerManager)
  2868.              },
  2869.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  2870.                contractID : "@mozilla.org/updates/update-manager;1",
  2871.                className  : "Update Manager",
  2872.                factory    : makeFactory(UpdateManager)
  2873.              },
  2874.   },
  2875.   
  2876.   canUnload: function(componentManager) {
  2877.     return true;
  2878.   }
  2879. };
  2880.  
  2881. /**
  2882.  * Creates a factory for instances of an object created using the passed-in
  2883.  * constructor.
  2884.  */
  2885. function makeFactory(ctor) {
  2886.   function ci(outer, iid) {
  2887.     if (outer != null)
  2888.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  2889.     return (new ctor()).QueryInterface(iid);
  2890.   } 
  2891.   return { createInstance: ci };
  2892. }
  2893.   
  2894. function NSGetModule(compMgr, fileSpec) {
  2895.   return gModule;
  2896. }
  2897.  
  2898. /**
  2899.  * Determines whether or there are installed addons which are incompatible 
  2900.  * with this update.
  2901.  * @param   update
  2902.  *          The update to check compatibility against
  2903.  * @returns true if there are no addons installed that are incompatible with
  2904.  *          the specified update, false otherwise.
  2905.  */
  2906. function isCompatible(update) {
  2907. //@line 2924 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2908.   var em = 
  2909.       Components.classes["@mozilla.org/extensions/manager;1"].
  2910.       getService(Components.interfaces.nsIExtensionManager);
  2911.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  2912.     nsIUpdateItem.TYPE_ADDON, false, { });
  2913.   return items.length == 0;
  2914. //@line 2933 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2915. }
  2916.  
  2917. /**
  2918.  * Shows a prompt for an update, provided there are no incompatible addons.
  2919.  * If there are, kick off an update check and see if updates are available
  2920.  * that will resolve the incompatibilities.
  2921.  * @param   update
  2922.  *          The available update to show
  2923.  */
  2924. function showPromptIfNoIncompatibilities(update) {
  2925.   function showPrompt(update) {
  2926.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  2927.     var prompter = 
  2928.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  2929.         createInstance(Components.interfaces.nsIUpdatePrompt);
  2930.     prompter.showUpdateAvailable(update);
  2931.   }
  2932.  
  2933. //@line 2952 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2934.   /**
  2935.    * Determines if an addon is compatible with a particular update.
  2936.    * @param   addon
  2937.    *          The addon to check
  2938.    * @param   version
  2939.    *          The extensionVersion of the update to check for compatibility 
  2940.    *          against.
  2941.    * @returns true if the addon is compatible, false otherwise
  2942.    */
  2943.   function addonIsCompatible(addon, version) {
  2944.     var vc = 
  2945.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  2946.         getService(Components.interfaces.nsIVersionComparator);
  2947.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  2948.           (vc.compare(version, addon.maxAppVersion) <= 0);
  2949.   }
  2950.  
  2951.   /**
  2952.    * An object implementing nsIAddonUpdateCheckListener that looks for 
  2953.    * available updates to addons and if updates are found that will make the 
  2954.    * user's installed addon set compatible with the update, suppresses the
  2955.    * prompt that would otherwise be shown.
  2956.    * @param   addons
  2957.    *          An array of incompatible addons that are installed.
  2958.    * @constructor
  2959.    */
  2960.   function Listener(addons) {
  2961.     this._addons = addons;
  2962.   }
  2963.   Listener.prototype = {
  2964.     _addons: null,
  2965.     
  2966.     /**
  2967.      * See nsIUpdateService.idl
  2968.      */
  2969.     onUpdateStarted: function() { 
  2970.     },
  2971.     onUpdateEnded: function() {
  2972.       // There are still incompatibilities, even after an extension update 
  2973.       // check to see if there were newer, compatible versions available, so
  2974.       // we have to prompt. 
  2975.       // 
  2976.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we 
  2977.       // handle incompatibilities:
  2978.       // 0    We count both VersionInfo updates _and_ NewerVersion updates
  2979.       //      against the list of incompatible addons installed - i.e. if
  2980.       //      Foo 1.2 is installed and it is incompatible with the update, and
  2981.       //      we find Foo 2.0 which is but which is not yet downloaded or 
  2982.       //      installed, then we do NOT prompt because the user can download
  2983.       //      Foo 2.0 when they restart after the update during the mismatch
  2984.       //      checking UI. This is the default, since it suppresses most 
  2985.       //      prompt dialogs. 
  2986.       // 1    We count only VersionInfo updates against the list of 
  2987.       //      incompatible addons installed - i.e. if the situation above
  2988.       //      with Foo 1.2 and available update to 2.0 applies, we DO show
  2989.       //      the prompt since a download operation will be required after
  2990.       //      the update. This is not the default and is supplied only as
  2991.       //      a hidden option for those that want it. 
  2992.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2993.                          INCOMPATIBLE_MODE_NEWVERSIONS);
  2994.       if ((mode == 0 && this._addons.length) || !isCompatible(update))
  2995.         showPrompt(update);
  2996.     },
  2997.     onAddonUpdateStarted: function(addon) {
  2998.     },
  2999.     onAddonUpdateEnded: function(addon, status) {
  3000.       if (status == Components.interfaces.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  3001.           addonIsCompatible(addon, update.extensionVersion)) {
  3002.         for (var i = 0; i < this._addons.length; ++i) {
  3003.           if (this._addons[i] == addon) {
  3004.             this._addons.splice(i, 1);
  3005.             break;
  3006.           }
  3007.         }
  3008.       }
  3009.     },
  3010.     /**
  3011.      * See nsISupports.idl
  3012.      */
  3013.     QueryInterface: function(iid) {
  3014.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  3015.           !iid.equals(Components.interfaces.nsISupports))
  3016.         throw Components.results.NS_ERROR_NO_INTERFACE;
  3017.       return this;
  3018.     }
  3019.   };
  3020.   
  3021.   if (!isCompatible(update)) {
  3022.     var em = 
  3023.         Components.classes["@mozilla.org/extensions/manager;1"].
  3024.         getService(Components.interfaces.nsIExtensionManager);
  3025.     var listener = new Listener(em.getIncompatibleItemList("", 
  3026.       update.extensionVersion, nsIUpdateItem.TYPE_ADDON, false, { }));
  3027.     // See documentation on |mode| above. 
  3028.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  3029.                        INCOMPATIBLE_MODE_NEWVERSIONS);
  3030.     em.update([], 0, mode != 0, listener);
  3031.   }
  3032.   else
  3033. //@line 3052 "/builds/tinderbox/Sb-Trunk/Linux_2.6.9-42.ELsmp_Depend/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  3034.     showPrompt(update);
  3035. }
  3036.